package fr.hoteia.appengine.archetype.server.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class UploadRemoteServlet extends HttpServlet {
	 
	private static final long serialVersionUID = 1L;
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private static ApplicationContext ctx = null;

	public void init(ServletConfig sc) throws ServletException {
		synchronized (UploadRemoteServlet.class) {
			super.init(sc);

			ServletContext context = getServletContext();
			ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
// 
//		ProductManager productManager = (ProductManager) ctx.getBean("productManager");
//		String productSkuGUID = request.getPathInfo().replace("/", "");
//		Product product = productManager.getProductByProductCode(productSkuGUID);
//		if(product != null){
//			
//			Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
//			BlobKey blobKey = blobs.get("uploadFormElement");
//
//			if(blobKey != null){
//				String oldBlobKey = product.getDefaultImageBlobKey();
//				product.setDefaultImageBlobKey(blobKey.getKeyString());
//				productManager.saveOrUpdateProduct(product);
//				
//				if(StringUtils.isNotEmpty(oldBlobKey)){
//					blobstoreService.delete(new BlobKey(oldBlobKey));
//				}
//			}
//		}
	}
 
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doGet(request, response);
	}
}